package com.ruoyi.common.gscUtil.StudyUtil.MultiDataSourceUtil.DynamicSwitchingUtil;

import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;

/**
 * 3.配置动态数据源
 *
 * 在需要切换数据源的地方，调用 DataSourceContextHolder2.setDataSourceKey("db1")
 * 或 DataSourceContextHolder2.setDataSourceKey("db2") 即可。
 */
//@Configuration
public class DynamicDataSourceConfig3 {

    @Bean
    public DataSource dynamicDataSource(
            @Qualifier("dataSource1") DataSource dataSource1,
            @Qualifier("dataSource2") DataSource dataSource2) {
        DynamicDataSource1 dynamicDataSource = new DynamicDataSource1();
        Map<Object, Object> targetDataSources = new HashMap<>();
        targetDataSources.put("db1", dataSource1);
        targetDataSources.put("db2", dataSource2);
        dynamicDataSource.setDefaultTargetDataSource(dataSource1); // 设置默认数据源
        dynamicDataSource.setTargetDataSources(targetDataSources);
        dynamicDataSource.afterPropertiesSet();
        return dynamicDataSource;
    }
}